import React, {Component, PropTypes} from 'react';
import {
    StyleSheet,
    Text,
    TouchableHighlight,
    TouchableOpacity,
    TouchableWithoutFeedback,
    Image,
    View,
    TextInput,
} from 'react-native';
import Util from './../../core/utils/util';

export default class CStepper extends Component {
    static propTypes = {
        style: PropTypes.any,
        textStyle: PropTypes.any,
        textFlex: PropTypes.number,
        showText: PropTypes.bool,
        editable: PropTypes.bool,
        initialValue: PropTypes.number,
        minimumValue: PropTypes.number,
        maximumValue: PropTypes.number,
        stepValue: PropTypes.number,
        backgroundColor: PropTypes.string,
        tintColor: PropTypes.string,
        borderColor: PropTypes.string,
        borderWidth: PropTypes.number,
        underlayColor: PropTypes.string,
        padding: PropTypes.number,
        valueChanged: PropTypes.func,
        tintOnIncrementImage: PropTypes.bool,
        tintOnDecrementImage: PropTypes.bool,
        imageHeight: PropTypes.number,
        imageWidth: PropTypes.number,
        incrementImage: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.number
        ]),
        decrementImage: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.number
        ]),
        disable: PropTypes.bool,
        editorModeChanged:PropTypes.func,
    }
    static defaultProps = {
        style: {},
        textStyle: {},
        textFlex: 1,
        showText: true,
        editable: true,
        initialValue: 0,
        minimumValue: 0,
        maximumValue: 10,
        stepValue: 1,
        backgroundColor: 'transparent',
        borderWidth:0,
        borderColor: '#F2F2F2',
        tintColor: '#F2F2F2',
        underlayColor: 'lightgray',
        valueChanged: null,
        decrementImage: require('./../../img/decrement.png'),
        incrementImage: require('./../../img/increment.png'),
        tintOnIncrementImage: true,
        tintOnDecrementImage: true,
        padding: 4,
        imageHeight: 32,
        imageWidth: 40,
        disable: false,
        editorModeChanged:null,
    }

    constructor(props) {
        super(props)
        this.state = {
            value: props.initialValue,
            inputValue:props.initialValue,
            decrementOpacity: 1,
            incrementOpacity: 1,
            hasReachedMin: false,
            hasReachedMax: false,
            inEditorMode: false,
        }

        //失效状态
        this.checkIsDisable();
        this.decrementAction = this.decrementAction.bind(this)
        this.incrementAction = this.incrementAction.bind(this)
        this.validateInitialValue = this.validateInitialValue.bind(this)
    }

    componentWillMount() {
        this.validateInitialValue(this.props.initialValue)
    }

    decrementAction() {
        var value = this.state.value
        var stepValue = this.props.stepValue
        value -= stepValue
        this.validateInitialValue(value)
    }

    incrementAction() {
        var value = this.state.value
        var stepValue = this.props.stepValue
        value += stepValue
        this.validateInitialValue(value)
    }

    setValue(value) {
        var maximumValue = this.props.maximumValue
        var minimumValue = this.props.minimumValue
        if (value >= maximumValue) {
            value = maximumValue // prevent overflow value
            this.setState({
                value: maximumValue,
                hasReachedMax: true,
                hasReachedMin: false,
                incrementOpacity: 0.5,
                decrementOpacity: 1
            })
        } else if (value <= minimumValue) {
            value = minimumValue // prevent overflow value
            this.setState({
                value: minimumValue,
                hasReachedMin: true,
                hasReachedMax: false,
                decrementOpacity: 0.5,
                incrementOpacity: 1
            })
        } else {
            this.setState({
                value: value,
                hasReachedMin: false,
                hasReachedMax: false,
                incrementOpacity: 1,
                decrementOpacity: 1
            })
        }

        //失效状态
        this.checkIsDisable();
    }

    checkIsDisable() {
        const {disable} = this.props
        if (disable) {
            this.setState({
                hasReachedMin: true,
                hasReachedMax: true,
                incrementOpacity: 0.5,
                decrementOpacity: 0.5
            })
        }
    }

    validateInitialValue(value) {
        this.setValue(value);
        if (this.props.valueChanged) {
            this.props.valueChanged(value, this)
        }
    }

    tintStyle(status) {
        if (status) {
            return {tintColor: this.props.tintColor}
        }
        return null
    }

    imageSrc(src) {
        if (typeof src == 'string') {
            return {'uri': src}
        }
        return src
    }

    imageStyle(src) {
        if (typeof src == 'string') {
            return {width: this.props.imageWidth, height: this.props.imageHeight}
        }
        return null
    }

    getLeftButtonBorderStyle() {
        if (this.props.showText) {
            return {borderRightWidth: 0}
        } else {
            return {borderRightWidth: 0}
        }
    }

    onPressMidText = () => {
        const {editable, disable} = this.props;
        const {value} = this.state;
        if (editable && !disable) {
            this.setState({
                inEditorMode: true,
                inputValue:value,
            })
        }
        this.onStepperEditorModeChanged(true);

    }

    onStepperEditorModeChanged(inEditorMode){
        const {editorModeChanged} = this.props;
        if(editorModeChanged){
            editorModeChanged(inEditorMode);
        }
    }

    onChangeInputText=(val)=>{
        this.setState({
            inputValue:val,
        });
    }
    //调整输入值到合适值
    justifyInputValue(val){
        let inRange = true;
        let rightValue = val;
        const {minimumValue,maximumValue} = this.props;
        if(val!=""){
            let numVal = parseInt(val)
            if(numVal<minimumValue){
                Util.showToast("超出最小范围")
                inRange = false;
                rightValue = minimumValue;
            }else if(numVal>maximumValue){
                inRange = false;
                Util.showToast("超出最大范围")
                rightValue = maximumValue;
            }else{
                rightValue = numVal;
            }
        }else{
            rightValue = this.state.value;
        }
        return rightValue;
    }

    onSubmitInputText=()=>{
        const {inputValue} = this.state;
        const rightValue = this.justifyInputValue(inputValue);
        this.validateInitialValue(rightValue);
        this.setState({
            inEditorMode:false,
        });
        this.onStepperEditorModeChanged(false);
    }

    blur=()=>{
        this.onSubmitInputText();
        alert("blur on cstepper");
    }

    genMidTextUI() {
        const {editable, disable, showText} = this.props;
        const {inEditorMode} = this.state;
        if (showText) {
            let textStyleIsDisable = null;
            if (disable) {
                textStyleIsDisable = styles.textStyleDisabled;
            }
            if (inEditorMode) {
                return (
                    <View style={[styles.midTextView,{flex:this.props.textFlex}]}>
                        <TextInput
                            underlineColorAndroid="transparent"
                            autoFocus={editable}
                            editable={editable}
                            keyboardType="numeric"
                            allowFontScaling={false}
                            style={[styles.midTextInput,this.props.textStyle,textStyleIsDisable]}
                            onChangeText={this.onChangeInputText}
                            onSubmitEditing={this.onSubmitInputText}
                            onBlur={this.onSubmitInputText}
                            returnKeyType="done"
                            value={this.state.inputValue+""}
                        ></TextInput>
                    </View>);
            } else {
                return (
                    <TouchableWithoutFeedback onPress={this.onPressMidText}>
                        <View style={[styles.midTextView,{flex:this.props.textFlex}]}>
                            <Text allowFontScaling={false}
                                  style={[styles.midText,this.props.textStyle,textStyleIsDisable]}>{this.state.value}</Text>
                        </View>
                    </TouchableWithoutFeedback>);
            }

        }
    }

    render() {
        const {
            tintOnIncrementImage,
            tintOnDecrementImage,
            decrementImage,
            incrementImage,
            borderWidth,
            borderColor,
            backgroundColor
        } = this.props;

        var tintIncrementStyle = this.tintStyle(tintOnIncrementImage);
        var tintDecrementStyle = this.tintStyle(tintOnDecrementImage);
        var decrementImageSrc = this.imageSrc(decrementImage);
        var incrementImageSrc = this.imageSrc(incrementImage);
        var incrementStyle = this.imageStyle(incrementImage);
        var decrementStyle = this.imageStyle(decrementImage);


        return (
            <View
                style={[styles.container, {backgroundColor: backgroundColor, borderColor:borderColor,borderWidth:borderWidth},this.props.style]}>
                <TouchableHighlight
                    style={[this.getLeftButtonBorderStyle(),styles.leftButton, {opacity: this.state.decrementOpacity, borderColor:borderColor,borderWidth:borderWidth, padding: this.props.padding}]}
                    underlayColor={this.props.underlayColor} onPress={this.decrementAction}
                    disabled={this.state.hasReachedMin}>
                    <Image style={[decrementStyle, tintDecrementStyle]} source={decrementImageSrc}/>
                </TouchableHighlight>
                {this.genMidTextUI()}
                <TouchableHighlight
                    style={[styles.rightButton, {opacity: this.state.incrementOpacity, borderColor: borderColor,borderWidth:borderWidth, padding: this.props.padding}]}
                    underlayColor={this.props.underlayColor} onPress={this.incrementAction}
                    disabled={this.state.hasReachedMax}>
                    <Image style={[incrementStyle, tintIncrementStyle]} source={incrementImageSrc}/>
                </TouchableHighlight>
            </View>
        )
    }
}

var styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        justifyContent: 'center',
        borderWidth: 1,
        borderRadius: 3,
        overflow: 'hidden',
        alignItems: 'center',
        backgroundColor: 'white',
        height:32,
    },
    leftButton: {
        width: 40,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#EEEEEE',
    },
    midText: {
        lineHeight:13,
        fontSize:13,
        textAlign:'center',
    },
    midTextInput: {
        flex:1,
        textAlign:'center',
        lineHeight:13,
        fontSize:13,
        // borderWidth: 1,
    },
    textStyleDisabled: {
        opacity: 0.5
    },
    midTextView: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    rightButton: {
        width: 40,
        alignItems: 'center',
        justifyContent: 'center',
        // borderLeftWidth: 1,
        backgroundColor: '#EEEEEE',
    }
})
